<!doctype html>
<html lang="zh-CN" th:replace="admin-layout :: layout(~{::title}, ~{}, ~{::script}, ~{::body}, 'exam-list')"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>考试试卷</title>
    <script>
        var $table = $("#table");
        var $remove = $("#removeBtn");
        var $update = $("#updateBtn");
        var $search = $("#searchBtn");
        var selections = [];
        var rows=[];
        var childIds=[];
        var childRows=[];

        $(function () {
            // tableList(columns)
        })

        var columns = [{
            checkbox: true
        }, {
            field: 'loginName',
            title: '账号',
            align: 'center',
        }, {
            field: 'name',
            title: '姓名',
            align: 'center',
        }, {
            field: 'gender',
            title: '性别',
            align: 'center',
            formatter: genderFormatter
        }, {
            field: 'type',
            title: '类型',
            align: 'center',
            formatter: typeFormatter
        }]

        function genderFormatter(value, row, index) {
            if (row.gender === "B") {
                return "男";
            } else if (row.gender === "C") {
                return "女";
            } else {
                return "外星人";
            }
        }

        function typeFormatter(value, row, index) {
            if (row.type === "A") {
                return "管理员";
            } else {
                return "普通用户";
            }
        }

        function detailFormatter(index, row) {
            console.log(row)
            var html = []
            $.each(row, function (key, value) {
                html.push('<p><b>' + key + ':</b> ' + value + '</p>')
            })
            return html.join('')
        }

        //操作按钮
        function operateFormatter(value, row, index) {
            return [
                '<a class="btn btn-primary btn-xs" href="/admin/user/update/' + row.id + '">修改</a>',
                '&nbsp;',
                '<a class="btn btn-primary btn-xs" href="/admin/user/reset/password/' + row.id + '">重置密码</a>',
                '&nbsp;',
                '<button type="button" class="btn btn-danger btn-xs removeBtn">删除</button>'
            ].join('')
        }

        //操作按钮事件
        window.operateEvents = {
            'click .removeBtn': function (e, value, row, index) {
                confirmAlert(function () {
                    ajaxJson("/admin/user/ajax/remove", {"id": row.id}, function (res) {
                        if (res.status) {
                            $table.bootstrapTable('remove', {
                                field: 'id',
                                values: [row.id]
                            })
                        }
                    })
                })
            }
        }

        $remove.click(function () {
            confirmAlert(function () {
                //移出子数据
                for (let i = 0; i < selections.length; i++) {
                    var paperId=selections[i];
                    var index=childIds.indexOf(paperId);
                    if (index>-1) {
                        childIds.splice(index,1);
                    }
                }
                $("#paperIds").val(childIds.toString());

                //移出子数据
                var childRowsCopy=[];
                for (let i = 0; i < childIds.length; i++) {
                    var paperId = childIds[i];
                    for (var j = 0; j < childRows.length; j++) {
                        var paper=childRows[j];
                        if(paperId===paper.id){
                            childRowsCopy.push(paper);
                            break;
                        }
                    }
                }
                childRows=childRowsCopy;

                //移出表格中的数据
                $table.bootstrapTable('remove', {
                    field: 'id',
                    values: selections
                })
            })
        })

        $update.click(function () {
            var ids = getIdSelections()
            if (ids) {
                location.href = "/admin/user/update/" + ids[0]
            }
        })

        function getIdSelections() {
            return $.map($table.bootstrapTable('getSelections'), function (row) {
                return row.id
            })
        }

        $table.on('check.bs.table uncheck.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table',
            function () {
                $remove.prop('disabled', !$table.bootstrapTable('getSelections').length)

                // save your data, here just save the current page
                selections = getIdSelections()
                // push or splice the selections if you want to save all data selections
            })
        $table.on('load-success.bs.table',function (e,data){
            for (var i = 0; i < data.length; i++) {
                var row=data[i];
                childIds.push(row.id);
                childRows.push(row);
            }
        })

        $search.click(function () {
            $table.bootstrapTable('refresh')
        })

        //选择用户
        $("#addPaperBtn").click(function(){
            layer.open({
                type: 2,
                area: ['60%', '99%'],
                scrollbar: false,
                btn: ['确定'],
                title: "选择试卷",
                yes: function(index, layero){
                    var contentWindow=$(layero).find("iframe")[0].contentWindow;
                    //获取选中id
                    childIds=contentWindow.selections;
                    $("#paperIds").val(childIds.toString());
                    //获取选中数据
                    childRows=contentWindow.rows;
                    //复选框设置为未勾选
                    for (var i = 0; i < childRows.length; i++) {
                        childRows[i].state=false;
                    }
                    //重新加载数据
                    $table.bootstrapTable('load', childRows);

                    //关闭窗口
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                },
                content: '/admin/exam/select/paper' //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
            });
        })

        function genderFormatter(value, row, index) {
            if (row.gender === "B") {
                return "男";
            } else if (row.gender === "C") {
                return "女";
            } else {
                return "外星人";
            }
        }

        function typeFormatter(value, row, index) {
            if (row.type === "A") {
                return "管理员";
            } else {
                return "普通用户";
            }
        }

        //保存按钮
        $("#savePaperBtn").click(function(){
            //获取用户数量
            $("#paperNum").val(childIds.length);
            //提交数据
            ajaxJson("/admin/exam/ajax/save/paper",$("#form").serialize(),function(res){
                if (res.status) {
                    history.back();
                }
            })
        });

        //响应数据
        function responseHandler(res) {
            return res.data
        }
    </script>
</head>
<body>
<div class="fyl-mb10">
    <form id="form">
        <input type="hidden" name="id" th:value="${examId}">
        <input type="hidden" id="paperNum" name="paperNum">
        <input type="hidden" id="paperIds" name="paperIds">
    </form>
    <form id="toolbar">
        <input type="hidden" name="page" id="page">
        <div class="row">
            <div class="col-sm-4 col-md-4 col-lg-2 fyl-mb10">
                <input type="text" class="form-control fyl-clear" name="name"
                       placeholder="试卷名称"
                       autocomplete="off">
            </div>
            <div class="col-sm-4 col-md-4 col-lg-2 fyl-mb10">
                <a href="javascript:void(0)" class="btn btn-primary" id="searchBtn">查询</a>
                <a href="javascript:void(0)" class="btn btn-warning" id="clearSearchBtn">清空</a>
            </div>
        </div>
    </form>
</div>
<div class="fyl-mb20">
    <button type="button" class="btn btn-primary" id="addPaperBtn">加卷</button>
    <button type="button" class="btn btn-primary" id="savePaperBtn">保存</button>
    <button type="button" class="btn btn-danger" id="removeBtn" disabled>删除</button>
</div>
<table
        id="table"
        data-toggle="table"
        data-method="post"
        data-click-to-select="true"
        data-pagination="true"
        data-query-params="queryParams"
        data-response-handler="responseHandler"
        th:data-url="@{/admin/exam/ajax/paper/list/{examId}(examId=${examId})}">
    <thead>
    <tr>
        <th data-checkbox="true" data-field="state"></th>
        <th data-field="name" data-halign="center" data-align="center">试卷名称</th>
        <th data-field="time" data-halign="center" data-align="center">答题时间</th>
        <th data-field="score" data-halign="center" data-align="center">考试总分</th>
        <th data-field="qstNum" data-halign="center" data-align="center">试题数量</th>
    </tr>
    </thead>
</table>
</body>
</html>